import {
  Breadcrumb,
  Button,
  Card,
  Form,
  Radio,
  DatePicker,
  Table,
  Tag,
  Space,
  message,
  Modal,
} from 'antd';

import React, { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import { delArticleByIdAPI, getArticleListAPI } from 'api/article';
import defaultImgSrc from 'assets/error.png';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import Channel from 'components/Channel';
import { history } from 'utils/history';

const { RangePicker } = DatePicker;

// 作业：
// 1. 删除要求二次确认
// 2. 删除后查询请求带上分页数据

// style={(paddingTop = '20px')}
export default function ArticleList(props) {
  // ref可以用来存储数据
  // 1. 创建ref，准备保存form数据
  const formDataRef = useRef();
  // 创建ref保存分页信息;
  const pageInfoRef = useRef({});

  const articleStatus = [
    { id: -1, name: '全部', color: 'magenta' },
    { id: 0, name: '草稿', color: 'orange' },
    { id: 1, name: '待审核', color: 'red' },
    { id: 2, name: '审核通过', color: 'green' },
    { id: 3, name: '审核失败', color: 'cyan' },
  ];

  const onFinish = (values) => {
    // 目标：转换数据格式
    // console.log('values  ----->  ', values);
    let formData = {
      ...values,
    };

    // 1. 如果status 为 -1 ,删掉status
    if (formData.status === -1) {
      delete formData.status;
      // console.log('fromData  ----->  ', formData);
    }

    // 2. 如果选了时间范围，转换键名
    // 🔔 不确定格式，要跟后台确定，字段名要与接口一模一样
    if (formData.date) {
      const begin_pubdate = formData.date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      const end_pubdate = formData.date[1]
        .endOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      formData.begin_pubdate = begin_pubdate;
      formData.end_pubdate = end_pubdate;
      delete formData.date;
    }
    // console.log('formData  ----->  ', formData);
    // 准备发请求给后台
    formData = JSON.parse(JSON.stringify(formData));
    formDataRef.current = formData;
    loadArticleList(formData);
    // console.log('formData --- ', formData);
  };

  // 2.声明状态存储频道列表
  // const [channels, setChannels] = useState([]);
  // const loadChannels = async () => {
  //   const res = await loadChannelAPI();
  //   setChannels(res.data.channels);
  // };

  // 2. 定义状态准备保存数据，💥 有分页信息以及文章列表
  const [articleData, setArticleData] = useState({});
  // 3. 定义异步方法，请求文章列表的异步方法
  // 4. 接收参数
  const loadArticleList = async (params) => {
    // 5. 调用请求文章列表的接口，下方的代码不用动
    const res = await getArticleListAPI(params);
    setArticleData(res.data);
  };

  const delArticleById = (id) => {
    Modal.confirm({
      title: '温馨提示',
      content: '确定要删除这条数据吗?',
      onOk: async () => {
        await delArticleByIdAPI(id);
        message.success('删除成功', 1);

        const formData = formDataRef.current || {};
        // 注意带上分页的数据上去
        console.log('pageInfoRef', pageInfoRef);
        loadArticleList({
          ...(formData === '' ? pageInfoRef.current : pageInfoRef.current - 1),
        });
      },
    });
  };

  // 3. 挂载后发请求
  useEffect(() => {
    // loadChannels();
    // 4. 挂载时调用查询请求
    loadArticleList();
  }, []);

  const handlePageChange = (page, per_page) => {
    pageInfoRef.current = { page, per_page };
    console.log('page', page, per_page);
    // 3. 分页查询时带上formData，💥注意筛选表单为空时做判断
    const formData = formDataRef.current || {};
    loadArticleList({ page, per_page, ...formData });
  };
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      // key: 'name',
      render: (value) => {
        // console.log('value --- ', value);
        console.log('102---', articleData.results);
        return value.images.length ? (
          <img src={value.images[0]} alt="" width={100} height={60} />
        ) : (
          <img src={defaultImgSrc} alt="" width={100} height={60} />
        );
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (value) => {
        const currentItem = articleStatus.find((item) => item.id === value);
        return <Tag color={currentItem.color}>{currentItem.name}</Tag>;
      },
      // key: 'address',
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
      // key: 'address',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
      // key: 'address',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
      // key: 'address',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
      // key: 'address',
    },

    // 1. 封装删除的请求放啊发
    // 2. 封装异步请求，删除成功后发送请求数据 💥 查数据时要带上表单数据，💥带上分页数据，传给后台
    // 3. 点击时发送删除请求，查询id

    {
      title: '操作',
      //  需要指定操作的key，可以用action
      key: 'action',
      // record代表的是整行数据组成的对象，通常我们可以从中取到id，作为一些操作的参数
      render: (value, record) => {
        return (
          <Space>
            {/* 💥注意Button按效果图调整对应的icon */}
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => props.history.push(`/edit/${record.id}`)}
            ></Button>
            <Button
              shape="circle"
              icon={<DeleteOutlined />}
              danger
              onClick={() => delArticleById(record.id)}
            ></Button>
          </Space>
        );
      },
    },
  ];

  return (
    <div
      style={{
        height: 'calc( 100vh - 64px )',
        overflow: 'auto',
        padding: '24px',
      }}
    >
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>列表页面</Breadcrumb.Item>
          </Breadcrumb>
        }
        bordered={false}
      >
        <Form
          onFinish={onFinish}
          autoComplete="off"
          initialValues={{
            status: -1,
          }}
        >
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败，不传为全部</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item label="频道" name="channel_id">
            {/* 3. 替换原本的写法 */}
            <Channel></Channel>
          </Form.Item>
          <Form.Item label="日期" name="date">
            <RangePicker />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
        <p>根据筛选条件共查询到 {articleData.total_count} 条结果：</p>
        <Table
          columns={columns}
          dataSource={articleData.results}
          rowKey="id"
          pagination={{
            onChange: handlePageChange,
            position: ['bottomCenter'],
            pageSize: articleData.per_page,
            current: articleData.page,
            total: articleData.total_count,
          }}
        />
      </Card>
    </div>
  );
}
